<?php
//店铺名
class App_Shop extends Data_Base
{
    protected static $_currentShopId = NULL;
    protected static $_currentShops = NULL;
    
    protected $_commTableName;
    protected $_commPrimaryKey;

    public function __construct ($nid)
    {
        $this->_nid = $nid;
        $this->_commTableName = 'shop_info';
        $this->_commPrimaryKey = 'id';
    }

    public static function currentShopId()
    {
        $directory = Request::initial()->directory();

        // 后台环境
        if ($directory == 'admin')
        {
            $shop = self::current();
            return Arr::get($shop, 'id', 0);
        }
        else
        // 前台环境
        {
            if (empty(self::$_currentShopId))
            {
                $shopId = Cookie::get('shopId');
                if (empty($shopId))
                {
                    $shopId = self::defaultShopId();
                    Cookie::set('shopId', $shopId);
                }

                self::$_currentShopId = $shopId;
            }

            return self::$_currentShopId;
        }
    }

    public static function setCurrentShopId($shopId)
    {
        self::$_currentShopId = $shopId;
        Cookie::set('shopId', $shopId);
    }

    public static function defaultShopId()
    {
        $shopId = DB::select('id')
            ->from('shop_info')
            ->order_by('created', 'asc')
            ->limit(1)
            ->execute()
            ->get('id');

        return $shopId;
    }

    public static function search ($key, $sort_by = NULL, $offset = 0, $limit = 10, $tag = NULL)
    {
        if (empty($sort_by))
            $sort_by = 'created_desc';

        list($sort, $by) = explode('_', $sort_by);

        $count = DB::select(DB::expr('count(`id`) as counts'))
            ->from('shop_info')
            ->where('shopName', 'like', "%$key%")
            ->or_where('shortDesc', 'like', "%$key%")
            ->execute()
            ->get('counts');

        $lists = DB::select()
            ->from('shop_info')
            ->where('shopName', 'like', "%$key%")
            ->or_where('shortDesc', 'like', "%$key%")
            ->order_by($sort, $by)
            ->offset($offset)
            ->limit($limit)
            ->execute()
            ->as_array();

        foreach ($lists as & $l)
        {
            unset($l['homeDesc']);
        }

        return array('total' => $count, 'list' => $lists);
    }





    // 当前访问的店
    public static function current ()
    {
        if (empty(self::$_currentShops))
        {
            $query = DB::select()
                ->from('shop_info')
                ->execute();

            $ret = array();
            foreach ($query as $rs)
            {
                $id = $rs['id'];
                $ret[$id] = $rs;
            }

            self::$_currentShops = $ret;
        }

        $shopId = App_Shop::currentShopId();
        return Arr::get(self::$_currentShops, $shopId, array());
    }

    public static function items ($offset = 0, $limit = 0)
    {
        $query = DB::select()
            ->from('shop_info')
            ->order_by('countsView', 'desc');

        if ($limit > 0)
            $query->offset($offset)->limit($limit);

        $query = $query->execute();
        return $query->as_array();
    }

    public static function options_shopNames()
    {
        $items  = self::items();
        $ret    = array();
        $shopId = App_Shop_Manager::currentShopId();
        foreach ($items as $rs)
        {
            $id = $rs['id'];
            $name = $rs['shopName'];
            if ($shopId > 0)
            {
                if ($shopId == $id)
                    $ret[$id] = $name;
            }
            else
            {
                $ret[$id] = $name;
            }
        }

        return $ret;
    }

	//收藏店铺
    public static function likeItemsByUid ($uid, $offset, $limit, $tag = NULL)
    {
        if ($uid == 0)
        {
            $count = 0;
            $list  = array();
        }
        else
        {
            $list = DB::select('a.*')
                ->from(array('shop_info', 'a'))
                ->join(array('user_v2_actions', 'b'), 'LEFT')
                ->on('b.type', '=', DB::expr("'shop'"))
                ->on('a.id', '=', 'b.nid')
                ->where('b.uid', '=', $uid)
                ->order_by('b.created', 'desc')
                ->offset($offset)
                ->limit($limit)->execute()->as_array();
            $count = count($list);
        }

        return array('total' => $count, 'list' => $list);
    }

    public static function name ($shopId)
    {
        $info = self::basicInfo($shopId, FALSE);
        return Arr::get($info, 'shopName', '');
    }

    public static function shopIcon ($shopId)
    {
        $info = self::basicInfo($shopId, FALSE);
        $icon = Arr::get($info, 'shopIcon', '');
        if (empty($icon))
            return '';
        else
        {
            if (preg_match('/^http/', $icon))
                return $icon;
            else
                return url::site($icon, 'http', FALSE);
        }
    }

    public static function countsInc ($nid, $type, $n)
    {
        DB::update('shop_info')
            ->set(array($type => DB::expr("`$type` + $n")))
            ->where('id', '=', $nid)
            ->execute();
    }

	//基本信息
    public static function basicInfo ($nid = 1, $include_goods = TRUE)
    {
        $info = DB::select()
            ->from('shop_info')
            ->where('id', '=', $nid)
            ->limit(1)
            ->execute()
            ->current();

        $ret = array(
            'shopId'    => $nid,
            'id'        => $nid,
            'shopName'  => Arr::get($info, 'shopName'),
            'shopIcon'  => Arr::get($info, 'shopIcon'),
            'shortDesc' => Arr::get($info, 'shortDesc'),
            'homeDesc'  => Arr::get($info, 'homeDesc'),
            'countsView'  => Arr::get($info, 'countsView'),
            'countsLike'  => Arr::get($info, 'countsLike'),
            'scoreGoods'  => Arr::get($info, 'scoreGoods'),
            'scoreService'=> Arr::get($info, 'scoreService'),
            'scoreDeliver'=> Arr::get($info, 'scoreDeliver'),
            'shopBanner'  => Arr::get($info, 'shopBanner'),
            'chatUser'    => Arr::get($info, 'chatUser'),
        );

        if ($include_goods)
            $ret['goodsItems'] = App_Hot::items('GOODS', 0, 2, $nid);

        return $ret;
    }

    public static function getLikeShop($currentShopId)
    {
        $query = DB::select('id')
            ->from('shop_info')
            ->where('id', '!=', $currentShopId)
            ->execute();

        $shopIds = array();
        foreach ($query as $rs)
        {
            $shopIds[] = $rs['id'];
        }

        shuffle($shopIds);
        if (empty($shopIds))
            $shopId = $currentShopId;
        else
            $shopId = $shopIds[0];

        return self::basicInfo($shopId);
    }

    public function like ($user)
    {
        $action = 'like';
        $nid    = $this->_nid;
        $column = 'countsLike';

        // user action
        if ($user->hasAction('shop', $this->_nid, $action))
        {
            $user->delAction('shop', $this->_nid, $action);
            $this->incColumnValue($nid, $column, -1);
        }
        else
        {
            $user->addAction('shop', $this->_nid, $action);
            $this->incColumnValue($nid, $column, 1);
        }
        
        return $this->getColumnValue($nid, $column);

    }

    public static function initChatUser ($shopId)
    {

        $shop = DB::select()
            ->from('shop_info')
            ->where('id', '=', $shopId)
            ->execute()
            ->current();

        $source     = 'mobile';
        $userId     = $shop['mobile'];
        $userToken  = md5('m4eeee');
        $userIcon   = $shop['shopIcon'];
        $userName   = $shop['shopName'];
        $userGender = 'f';
        $userPushId = '';
        
        $user = user::initUserFromBasicInfo ($source, $userId, $userToken, $userName, $userIcon, $userGender, $userPushId);
        $uid  = $user->getUserUid();
        if ($uid > 0)
        {
            $chatUser = 'user'.$uid;
            DB::update('shop_info')
                ->set(array('chatUser' => $chatUser))
                ->where('id', '=', $shopId)
                ->execute();
        }
    }
}

